package com.example.club.encapsulation

import android.content.Context
import android.os.Handler
import android.os.Looper
import android.util.AttributeSet
import android.view.LayoutInflater
import android.widget.FrameLayout
import androidx.viewpager2.widget.ViewPager2
import com.example.club.R
import com.example.club.adapter.BannerAdapter
import com.example.club.model.BannerItem

class BannerView @JvmOverloads constructor(
    context: Context,
    attrs: AttributeSet? = null,
    defStyleAttr: Int = 0
) : FrameLayout(context, attrs, defStyleAttr) {

    private var viewPager: ViewPager2
    private var handler: Handler? = null
    private var runnable: Runnable? = null
    private var position = 0
    private var bannerList: List<BannerItem> = emptyList()

    init {
        LayoutInflater.from(context).inflate(R.layout.view_banner, this, true)
        viewPager = findViewById(R.id.banner_inner_viewpager)
    }

    fun setBannerList(list: List<BannerItem>) {
        bannerList = list
        viewPager.adapter = BannerAdapter(bannerList)
        startAutoPlay()
    }

    private fun startAutoPlay() {
        stopAutoPlay()
        handler = Handler(Looper.getMainLooper())
        runnable = object : Runnable {
            override fun run() {
                if (bannerList.isNotEmpty()) {
                    position = (viewPager.currentItem + 1) % bannerList.size
                    viewPager.currentItem = position
                    handler?.postDelayed(this, 3000)
                }
            }
        }
        handler?.postDelayed(runnable!!, 3000)
    }

    fun stopAutoPlay() {
        handler?.removeCallbacks(runnable!!)
    }

    override fun onDetachedFromWindow() {
        super.onDetachedFromWindow()
        stopAutoPlay()
    }
} 